﻿using Abp.Application.Services.Dto;
using Abp.AutoMapper;
using Abp.Threading;
using AutoMapper;
using MyCompanyName.AbpZeroTemplate.Agent.Dto;
using MyCompanyName.AbpZeroTemplate.Authorization.Users;
using MyCompanyName.AbpZeroTemplate.IRepositorys;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyCompanyName.AbpZeroTemplate.Agent
{
    public class AgentService : AbpZeroTemplateAppServiceBase, IAgentService
    {
        private readonly IAgentRepository _agentRepository;
        private readonly IAgentTransferRepository _agentTransferRepository;
        private readonly IAgentRechargeRepository _agentRechargeRepository;
        public AgentService(IAgentRepository agentRepository,
                            IAgentTransferRepository agentTransferRepository,
                            IAgentRechargeRepository agentRechargeRepository)
        {
            this._agentRepository = agentRepository;
            this._agentTransferRepository = agentTransferRepository;
            this._agentRechargeRepository = agentRechargeRepository;
        }

        /// <summary>
        /// 根据代理商名称获得用户的信息
        /// </summary>
        /// <param name="AccountCode"></param>
        /// <returns></returns>
        public User GetUserIdByAgentCode(string AgentCode)
        {
            User user = null;
            user = UserManager.Users.Where(m => m.UserName == AgentCode).FirstOrDefault();
            return user;
        }

        /// <summary>
        /// 根据账号获取信息
        /// </summary>
        /// <param name="Account"></param>
        /// <returns></returns>
        public AgentDto GetAgentByAgentCode(string agentCode)
        {
            var obj = _agentRepository.GetAll().Where(p => p.AgentCode.Equals(agentCode) || p.AgentName.Equals(agentCode)).FirstOrDefault();
            return obj.MapTo<AgentDto>();
        }

        /// <summary>
        /// 根据当前用户获得该用户的下级代理商
        /// </summary>
        /// <returns></returns>
        public List<string> GetAgentCodeByCurrentUser()
        {
            List<string> list = new List<string>();
            var currentUser = AsyncHelper.RunSync(this.GetCurrentUserAsync);

            var obj = _agentRepository.GetAll();

            //判断逻辑
            if (currentUser.UserName != "admin")
            {
                obj = obj.Where(t => t.FirstAgentCode == currentUser.UserName || t.SecondAgentCode == currentUser.UserName || t.AgentCode == currentUser.UserName);
            }

            //默认的分页方式
            var dataList = obj.ToList();

            foreach (var item in dataList)
            {
                list.Add(item.AgentCode);
            }

            return list;
        }

        #region 代理商
        /// <summary>
        /// 获得代理商列表
        /// </summary>
        /// <returns></returns>
        public PagedResultDto<AgentDto> GetAgentDtoList(string AgentName, int PageSize, int PageNumber)
        {
            var currentUser = AsyncHelper.RunSync(this.GetCurrentUserAsync);

            var obj = _agentRepository.GetAll();

            //判断逻辑
            if (currentUser.UserName != "admin")
            {
                obj = obj.Where(t => t.FirstAgentCode == currentUser.UserName || t.SecondAgentCode == currentUser.UserName || t.AgentCode == currentUser.UserName);
            }

            //获取总数
            var dataCount = obj.Count();

            //默认的分页方式
            var dataList = obj.Where(m => m.AgentName.Contains(AgentName) || m.AgentCode.Contains(AgentName))
                              .OrderByDescending(t => t.CreationTime)
                              .Skip(PageSize * (PageNumber - 1)).Take(PageSize).ToList();
            return new PagedResultDto<AgentDto>(dataCount, dataList.MapTo<List<AgentDto>>());


        }

        /// <summary>
        /// 创建代理商
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public int CreateAgent(CreateAgentInput input)
        {
            int result = 0;

            var task = Mapper.Map<Agent>(input);
            task.CreationTime = DateTime.Now;
            task.UpdateTime = DateTime.Now;

            result = _agentRepository.InsertAndGetId(task);


            return result;
        }
        /// <summary>
        /// 更新代理商
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public bool UpdateAgent(UpdateAgentInput input)
        {
            bool result = false;
            try
            {
                //获取当前用户
                var currentUser = AsyncHelper.RunSync(this.GetCurrentUserAsync);
                var obj = _agentRepository.Get(input.ID);
                obj.AgentCode = input.AgentCode;
                obj.AgentName = input.AgentName;
                obj.Address = input.Address;
                obj.TelePhone = input.TelePhone;
                obj.IdCard = input.IdCard;
                obj.AlipayAccount = input.AlipayAccount;
                obj.BankName = input.BankName;
                obj.BankAccount = input.BankAccount;
                obj.Remark = input.Remark;
                obj.Proportion = input.Proportion;

                obj.UpdateTime = DateTime.Now;
                //var updateObj = Mapper.Map<FLowSet>(input);
                //_flowSetRepository.Update(updateObj);
                result = true;
            }
            catch (Exception ex)
            {
                result = false;
            }
            return result;
        }

        /// <summary>
        /// 删除代理商
        /// </summary>
        /// <param name="AgentId"></param>
        /// <returns></returns>
        public bool DeleteAgent(int AgentId)
        {
            bool result = false;

            return result;
        }


        /// <summary>
        /// 根据代理商主键id获得代理商信息
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public AgentDto GetAgentById(int Id)
        {
            AgentDto result = new AgentDto();

            var obj = _agentRepository.Get(Id);
            result = obj.MapTo<AgentDto>();
            return result;
        }

        #endregion

        #region 代理商转账
        /// <summary>
        /// 获得代理商转账记录列表
        /// </summary>
        /// <returns></returns>
        public PagedResultDto<AgentTransferDto> GetAgentTransferDtoList(string AgentTransferName, int PageSize, int PageNumber)
        {
            var currentUser = AsyncHelper.RunSync(this.GetCurrentUserAsync);
            List<string> listAgentCode = GetAgentCodeByCurrentUser();
            var obj = _agentTransferRepository.GetAll();

            //获取总数
            var dataCount = obj.Count();
            //判断逻辑
            if (currentUser.UserName != "admin")
            {
                foreach (var item in listAgentCode)
                {
                    obj = obj.Where(t => t.RechargeAgentCode.Contains(item));
                }
            }

            //默认的分页方式
            var dataList = obj.Where(m => m.ReceiveRechargeAgentCode.Contains(AgentTransferName) || m.RechargeAgentCode.Contains(AgentTransferName))
                             .OrderByDescending(t => t.CreationTime)
                             .Skip(PageSize * (PageNumber - 1)).Take(PageSize).ToList();

            return new PagedResultDto<AgentTransferDto>(dataCount, dataList.MapTo<List<AgentTransferDto>>());
        }

        /// <summary>
        /// 创建经销商转账记录,更新代理商信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public string CreateAgentTransfer(CreateAgentTransferInput input)
        {
            bool flag = true;
            string resultStr = "";
            string ErrorMsg = "";
            try
            {
                //获取当前用户
                var currentUser = AsyncHelper.RunSync(this.GetCurrentUserAsync);
                var obj = Mapper.Map<AgentTransfer>(input);
                obj.OwnerId = currentUser.Id.ToString();
                obj.RechargeAgentCode = currentUser.UserName;
                obj.Operator = currentUser.UserName;
                obj.CreatedOn = DateTime.Now;
                obj.CreationTime = DateTime.Now;
                obj.UpdateTime = DateTime.Now;
                //1、更新代理商记录
                //1.1、当前代理商
                //var Currentobj = _agentRepository.Get(Convert.ToInt32(obj.OwnerId));
                var Currentobj = _agentRepository.GetAll().Where(t => t.AgentCode == currentUser.UserName).FirstOrDefault();
                var AgentTransferobj = _agentRepository.GetAll().Where(t => t.AgentCode == obj.ReceiveRechargeAgentCode).FirstOrDefault();
                if (AgentTransferobj != null)
                {
                    if (Convert.ToDouble(Currentobj.Balance) >= obj.Quantity)
                    {
                        Currentobj.Balance = Currentobj.Balance - Convert.ToDecimal(obj.Quantity);
                        AgentTransferobj.Balance = AgentTransferobj.Balance + Convert.ToDecimal(obj.Quantity);
                        //2、创建转账记录
                        int _result = _agentTransferRepository.InsertAndGetId(obj);
                        //resultStr = "转账成功";l
                        ErrorMsg = "转账成功";
                    }
                    else
                    {
                        flag = false;
                        ErrorMsg = "转账流量超过余额";
                    }
                }
                else
                {
                    flag = false;
                    ErrorMsg = "没有此代理商的账号";
                }
            }
            catch (Exception ex)
            {
                flag = false;
                ErrorMsg = ex.Message;
            }
            return "{\"status\":\"" + flag + "\",\"errormsg\":\"" + ErrorMsg + "\"}";
        }

        #endregion

        #region 代理商充值
        /// <summary>
        /// 获得代理商充值记录列表
        /// </summary>
        /// <returns></returns>
        public PagedResultDto<AgentRechargeDto> GetAgentRechargeDtoList(string AgentRechargeName, int PageSize, int PageNumber)
        {
            var obj = _agentRechargeRepository.GetAll();

            //获取总数
            var dataCount = obj.Count();

            //默认的分页方式
            var dataList = obj.Where(m => m.AgentCode.Contains(AgentRechargeName))
                              .OrderByDescending(t => t.CreationTime)
                              .Skip(PageSize * (PageNumber - 1)).Take(PageSize).ToList();

            return new PagedResultDto<AgentRechargeDto>(dataCount, dataList.MapTo<List<AgentRechargeDto>>());
        }

        /// <summary>
        /// 创建经销商充值记录,更新代理商信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public string CreateAgentRecharge(CreateAgentRechargeInput input)
        {
            bool flag = true;
            string resultStr = "";
            string ErrorMsg = "";
            try
            {
                //获取当前用户
                var currentUser = AsyncHelper.RunSync(this.GetCurrentUserAsync);
                var obj = Mapper.Map<AgentRecharge>(input);
                obj.OwnerId = currentUser.Id.ToString();
                obj.CreationTime = DateTime.Now;
                obj.UpdateTime = DateTime.Now;
                //1、更新代理商记录
                //1.1、当前代理商
                var AgentRechargeobj = _agentRepository.GetAll().Where(t => t.AgentCode == obj.AgentCode).FirstOrDefault();
                if (AgentRechargeobj != null)
                {
                    AgentRechargeobj.BalanceRecharge = AgentRechargeobj.BalanceRecharge + Convert.ToDecimal(obj.Amount);
                    //2、创建转账记录
                    int _result = _agentRechargeRepository.InsertAndGetId(obj);
                    //resultStr = "转账成功";l
                    ErrorMsg = "充值成功";

                }
                else
                {
                    flag = false;
                    ErrorMsg = "没有此代理商的账号";
                }
            }
            catch (Exception ex)
            {
                flag = false;
                ErrorMsg = ex.Message;
            }
            return "{\"status\":\"" + flag + "\",\"errormsg\":\"" + ErrorMsg + "\"}";
        }
    }
    #endregion
}
